import React, { useState, useEffect } from 'react';
import { Modal, Tree, Spin, message, Alert } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { getPlanPermissions, getAvailablePermissions, assignPermissions } from './permission-api';

interface PermissionModalProps {
  visible: boolean;
  planId: string;
  planName: string;
  onClose: () => void;
}

interface PermissionModule {
  module: string;
  moduleName: string;
  permissions: Array<{
    id: string;
    resource: string;
    action: string;
    description: string;
  }>;
}

const PermissionModal: React.FC<PermissionModalProps> = ({
  visible,
  planId,
  planName,
  onClose,
}) => {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  // 加载权限数据
  useEffect(() => {
    if (visible && planId) {
      loadPermissions();
    }
  }, [visible, planId]);

  const loadPermissions = async () => {
    setLoading(true);
    try {
      // 并行加载所有可用权限和套餐已分配权限
      const [availableRes, assignedRes] = await Promise.all([
        getAvailablePermissions(),
        getPlanPermissions(planId),
      ]);

      if (availableRes.data.success && assignedRes.data.success) {
        const modules: PermissionModule[] = availableRes.data.data;
        const assignedPermissions = assignedRes.data.data || [];
        const assignedIds = new Set(assignedPermissions.map((p: any) => p.id));

        // 构建树形数据
        const tree: DataNode[] = modules.map((module) => ({
          title: module.moduleName,
          key: module.module,
          children: module.permissions.map((perm) => ({
            title: `${perm.description} (${perm.resource}:${perm.action})`,
            key: perm.id,
          })),
        }));

        setTreeData(tree);
        setCheckedKeys(Array.from(assignedIds));
        setExpandedKeys(modules.map((m) => m.module));
      }
    } catch (error) {
      console.error('Failed to load permissions:', error);
      message.error('加载权限失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      // 过滤掉模块key，只保留权限ID
      const permissionIds = checkedKeys.filter((key) =>
        key.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)
      );

      await assignPermissions({
        planId,
        permissionIds,
      });

      message.success('权限分配成功');
      onClose();
    } catch (error) {
      console.error('Failed to assign permissions:', error);
      message.error('权限分配失败');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      title={`配置套餐权限 - ${planName}`}
      open={visible}
      onCancel={onClose}
      onOk={handleSave}
      confirmLoading={saving}
      width={600}
      destroyOnClose
    >
      <Alert
        message="提示"
        description="为套餐配置权限后，订阅该套餐的租户将自动获得这些权限。系统权限（如租户管理、套餐管理）不可分配。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Spin spinning={loading}>
        <div style={{ maxHeight: '500px', overflow: 'auto' }}>
          <Tree
            checkable
            treeData={treeData}
            checkedKeys={checkedKeys}
            expandedKeys={expandedKeys}
            onCheck={(checked) => {
              if (Array.isArray(checked)) {
                setCheckedKeys(checked as string[]);
              } else {
                setCheckedKeys(checked.checked as string[]);
              }
            }}
            onExpand={(expanded) => {
              setExpandedKeys(expanded as string[]);
            }}
          />
        </div>
      </Spin>
    </Modal>
  );
};

export default PermissionModal;

